package com.lance.core.es;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author alonecong@gmail.com
 *
 * es的高级client rest api
 */
@Slf4j
@Component
public class ElasticBean {
    /**
     * 创建客户端,高级api中引用低级builder,高级client关闭时候，内部会释放低级的连接池等信息
     * @see <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html></a>
     */
    public   RestHighLevelClient  creatClient(){


//        client.close();
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    }

    public IndexRequest createIndex() {
        //1.通过json 字符串直接创建index
        String json = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        return new IndexRequest("post").id("1").type("user")
                .source(json, XContentType.JSON);
    }
    //2.通过map创建
    public IndexRequest createIndexFromMap() {

        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        return new IndexRequest("post").id("1")
                .source(jsonMap);
    }
    //3.builder创建
    public IndexRequest createIndexFromBuilder() throws IOException {

        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.field("user", "kimchy");
            builder.timeField("postDate", new Date());
            builder.field("message", "trying out Elasticsearch");
        }
        builder.endObject();
        return new IndexRequest("posts").id("1").source(builder);
    }
    //key-pairs
    public IndexRequest createIndexFromKeypairs() {
        return new IndexRequest("posts")
                .id("1")
                .source("user", "kimchy",
                        "postDate", new Date(),
                        "message", "trying out Elasticsearch");
        //一些可以设置的参数
//        request.routing("routing");
//        request.timeout("1s");
//        request.setRefreshPolicy("wait_for");
//        request.version(2);
//
//        request.setPipeline("pipeline");

    }
    public void finalCreat(IndexRequest request) throws IOException {
        RestHighLevelClient client = creatClient();
//     IndexResponse indexResponse =  client.index(request, RequestOptions.DEFAULT);

        ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                log.info(" indexAsync create index  {}",indexResponse.getResult());
            }

            @Override
            public void onFailure(Exception e) {
                log.info(" indexAsync create failure result {}", e.getMessage());
            }
        };
        client.indexAsync(request, RequestOptions.DEFAULT, listener);

//        String index = indexResponse.getIndex();
//        String id = indexResponse.getId();
//        if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
//            log.info("create index = {} id = {} and result = {}",index,id,indexResponse.getResult());
//        } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//            log.info("update index = {} id = {} and result = {}",index,id,indexResponse.getResult());
//        }
//        ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
//        if(shardInfo.getTotal() != shardInfo.getSuccessful()) {
//            log.error("shard-total {} not equals success-count {} ",shardInfo.getTotal(),shardInfo.getSuccessful());
//        }
//
//        if (shardInfo.getFailed() > 0) {
//            for (ReplicationResponse.ShardInfo.Failure failure :
//                    shardInfo.getFailures()) {
//                String reason = failure.reason();
//                log.error("fail reason is {}" ,reason);
//            }
//        }

    }
    public void getDocumentApi() throws IOException {
        GetRequest request = new GetRequest("post","user","1");

        String[] includes = new String[]{"user","kimchy"};
        String[] excludes = Strings.EMPTY_ARRAY;

        FetchSourceContext context = new FetchSourceContext(true,includes,excludes);
//        FetchSourceContext.DO_NOT_FETCH_SOURCE  如果不进行包含和排除操作，可以使用获取源的默认值
        request.fetchSourceContext(context);

        GetResponse getResponse = creatClient().get(request,RequestOptions.DEFAULT);
        String index = getResponse.getIndex();
        String type = getResponse.getType();
        String id = getResponse.getId();
        if (getResponse.isExists()) {
            long version = getResponse.getVersion();
            String sourceAsString = getResponse.getSourceAsString();
            Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
            byte[] sourceAsBytes = getResponse.getSourceAsBytes();
        } else {
            log.info("the document is exist");
        }

    }
}
